<!-- PlantDisplay.vue -->

<template>
  <div class="box">
    <!-- <h1>植物展示</h1> -->
    <!-- 搜索按钮 -->
    <el-input
      v-model="searchKeyword"
      style="margin-right: 20px;width: 600px;
    margin-left: 10px;
    float: left;"
      placeholder="请输入中文名或者拉丁名"
      class="input-with-select"
    >
      <el-button slot="append" @click="handleSearch">搜索</el-button>
    </el-input>

    <!-- 高级搜索 -->

    <el-button
      type="primary"
      style="margin-right: 10px;display: none;"
      @click="dialogFormVisible = true"
      >高级搜索</el-button
    >

    <el-dialog
      title="高级搜索"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose"
    >
      <div class="dialog-content">
        <el-form
          :model="formData"
          label-position="left"
          :inline="true"
          class="demo-form-inline"
        >
          <el-row>
            <el-col :xs="24" :sm="12">
              <el-form-item
                label="是否列入国家保护等级"
                :label-width="labelWidth"
              >
                <el-select
                  v-model="selectedOption1"
                  placeholder="请选择"
                  @change="handleOptionChange1"
                >
                  <el-option
                    v-for="list in list1"
                    :key="list.value"
                    :label="list.label"
                    :value="list.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item
                label="是否红色名录濒危等级"
                :label-width="labelWidth"
              >
                <el-select
                  v-model="selectedOption2"
                  placeholder="请选择"
                  @change="handleOptionChange2"
                >
                  <el-option
                    v-for="list in list2"
                    :key="list.value"
                    :label="list.label"
                    :value="list.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12">
              <el-form-item label="是否中国特有" :label-width="labelWidth">
                <el-select
                  v-model="selectedOption3"
                  placeholder="请选择"
                  @change="handleOptionChange3"
                >
                  <el-option
                    v-for="list in list3"
                    :key="list.value"
                    :label="list.label"
                    :value="list.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="是否城市特有" :label-width="labelWidth">
                <el-select
                  v-model="selectedOption4"
                  placeholder="请选择"
                  @change="handleOptionChange4"
                >
                  <el-option
                    v-for="list in list4"
                    :key="list.value"
                    :label="list.label"
                    :value="list.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12">
              <el-form-item label="是否自治区特有" :label-width="labelWidth">
                <el-select
                  v-model="selectedOption5"
                  placeholder="请选择"
                  @change="handleOptionChange5"
                >
                  <el-option
                    v-for="list in list5"
                    :key="list.value"
                    :label="list.label"
                    :value="list.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item
                label="分布中心是否在保护地"
                :label-width="labelWidth"
              >
                <el-select
                  v-model="selectedOption6"
                  placeholder="请选择"
                  @change="handleOptionChange6"
                >
                  <el-option
                    v-for="list in list6"
                    :key="list.value"
                    :label="list.label"
                    :value="list.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12">
              <el-form-item label="是否外来物种" :label-width="labelWidth">
                <el-select
                  v-model="selectedOption7"
                  placeholder="请选择"
                  @change="handleOptionChange7"
                >
                  <el-option
                    v-for="list in list7"
                    :key="list.value"
                    :label="list.label"
                    :value="list.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="属名称" :label-width="labelWidth">
                <el-cascader
                  v-model="formData.sdm"
                  placeholder="搜索"
                  :options="options"
                  filterable
                  :show-all-levels="false"
                  @change="handleCascaderChange"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer" style="text-align: center">
          <!-- <el-button @click="dialogFormVisible = false">取 消</el-button> -->

          <!-- 取消按钮 -->
          <el-button @click="handleDialogClose">取消</el-button>

          <el-button type="primary" @click="handleAdvancedSearch"
            >搜索</el-button
          >
          <el-button type="success" @click="handleClear">重置</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 新增按钮 -->
    <el-button type="primary" @click="handleAddPlant">新增</el-button>
    <!-- Excel批量导入按钮 -->
    <el-button
      type="success"
      style="margin-left: 10px"
      @click="handleExcelImport"
    >
      <i class="el-icon-upload2" />
      Excel批量导入
    </el-button>

    <!-- 显示加载状态 -->
    <!-- <div style="margin-top: 50px" v-if="loading">加载中...</div> -->

    <!-- 显示植物数据 -->
    <div
      v-loading="loading"
      style="margin-top: 20px"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 1)"
    >
      <div
        v-if="filteredPlants.length > 0"
        :class="['plant-container', containerClass]"
        :style="plant_container_style"
      >
        <plant-item
          v-for="plant in filteredPlants"
          :key="plant.id"
          :plant="plant"
          style="cursor: pointer"
          @plantDeleted="handlePlantDeleted"
        />
      </div>
      <div
        v-else
        style="
          height: 400px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 25px;
        "
      >
        暂无数据
      </div>
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalPlant"
       :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- Excel导入数据展示弹框 -->
    <el-dialog
      title="Excel数据预览"
      :visible.sync="excelImportDialogVisible"
      width="90%"
      :close-on-click-modal="false"
      @close="handleExcelDialogClose"
    >
      <div class="excel-preview-container">
        <el-table
          :data="paginatedExcelData"
          border
          stripe
          style="width: 100%"
          max-height="500"
          :header-cell-style="{
            fontWeight: 'bold',
            backgroundColor: '#f5f7fa',
          }"
        >
          <el-table-column
            v-for="header in excelHeaders || []"
            :key="header.key"
            :prop="header.prop"
            :label="header.label"
            min-width="120"
            show-overflow-tooltip
          />
        </el-table>

        <div class="excel-pagination">
          <el-pagination
            :current-page="excelCurrentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="excelPageSize"
            :total="excelData ? excelData.length : 0"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleExcelSizeChange"
            @current-change="handleExcelCurrentChange"
          />
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleExcelDialogClose">关闭</el-button>
        <el-button type="primary" @click="handleConfirmImport"
          >确认导入</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import PlantItem from "@/views/SpeciesLibrary/PlantLibrary/PlantItem/index";
import * as XLSX from "xlsx";
import commonOper from "../../../utils/commonOper";
import { readPlantBasicInfo } from '../../../utils/readPlantExcel.js';
import config from "@/config/config.js";
import { getToken } from '@/utils/auth' ;
export default {
  components: {
    PlantItem,
  },
  data() {
    return {
      plants: [
        {
          alien: null,
          aliendamage: null,
          centerinprotected: null,
          centerposition: null,
          characteristics: null,
          countryjb: null,
          countryjbdm: null,
          ecologicalwatertypes: null,
          endangered: null,
          floristicgeographiccompositions: null,
          habita: null,
          id: null,
          imgbasestr: null,
          ischina: null,
          ischinadm: null,
          iscites: null,
          iscitesdm: null,
          jlr: null,
          laiyuan: null,
          lifeformgroups: null,
          mainvalue: null,
          pcpath: null,
          proprotected: null,
          protectionlevel: null,
          protectstatus: null,
          provinceunique: null,
          redjb: null,
          redjbdm: null,
          sdm: null,
          shengjinzhaopian: null,
          shx: null,
          shxdm: null,
          smc: null,
          specimedm: null,
          stx: null,
          stxdm: null,
          tuming: null,
          updatetime: null,
          wzdm: null,
          wzmc: null,
          wzsm: null,
          xmc: null,
          zpcpath: null,
          zwzpage: null,
        },
      ],
      // 高级搜索
      formData: {
        alien: null,

        centerinprotected: null,

        countryjb: null,
        countryjbdm: null,

        ischina: null,
        ischinadm: null,
        iscites: null,
        iscitesdm: null,
        jlr: null,

        provinceunique: null,
        redjb: null,
        redjbdm: null,
        sdm: null,

        smc: null,

        tuming: null,

        wzmc: null,

        xmc: null,
      },

      plant_container_style:"max-height:620px",
      currentPage: 1,
      pageSize: 10, // 每页显示 4 个植物，即每页两行
      totalPlant:0,
      loading: true, // 新增加载状态
      searchKeyword: "", // 新增搜索关键词

      filteredPlants: [],

      dialogFormVisible: false,
      selectedOption1: "", // 是否国家保护等级
      selectedOption2: "", // 是否红色名录濒危等级
      selectedOption3: "", // 是否中国特有
      selectedOption4: "", // 是否城市特有
      selectedOption5: "", // 是否自治区特有
      selectedOption6: "", // 分布中心是否在保护地
      selectedOption7: "", // 是否外来物种
      options: [], // 用于存储层级数据
      filteredData: [], // 所有属数据
      displayType: "全部", // 默认显示全部数据
      displayTypeOptions: ["全部", "植物"],
      labelWidth: "155px",

      list1: [
        { label: "一级", value: "01" },
        { label: "二级", value: "02" },
        { label: "未列入", value: "03" },
      ],
      list2: [
        { label: "濒危(EN)", value: "01" },
        { label: "地区绝灭(RE)", value: "02" },
        { label: "极危(CR)", value: "03" },
        { label: "近危(NT)", value: "04" },
        { label: "数据缺乏(DD)", value: "05" },
        { label: "未予评估(NE)", value: "06" },
        { label: "无危(LC)", value: "07" },
        { label: "易危(VU)", value: "08" },
      ],
      list3: [
        { label: "是", value: "01" },
        { label: "否", value: "02" },
      ],
      list4: [
        { label: "附录Ⅰ", value: "01" },
        { label: "附录Ⅱ", value: "02" },
        { label: "未列入", value: "03" },
      ],
      list5: [
        { label: "是", value: "01" },
        { label: "否", value: "02" },
      ],
      list6: [
        { label: "是", value: "01" },
        { label: "否", value: "02" },
      ],
      list7: [
        { label: "是", value: "01" },
        { label: "否", value: "02" },
      ],

      // Excel导入相关
      excelImportDialogVisible: false,
      excelData: [],
      excelHeaders: [{key:1,prop:"chineseName",label:"中文名"},{key:2,prop:"scientificName",label:"学名"},
        {key:3,prop:"familyChinese",label:"科名（中文名）"},{key:4,prop:"familyLatin",label:"科名（学名）"},
        {key:5,prop:"genusChinese",label:"属名（中文名）"},{key:6,prop:"genusLatin",label:"属名（学名）"},
        {key:7,prop:"lifeForm1",label:"生活型1"},{key:8,prop:"lifeForm2",label:"生活型2"},
        {key:9,prop:"moistureType",label:"水分生态类型"},{key:10,prop:"floristicComponent",label:"区系地理成分"},
        {key:11,prop:"isExotic",label:"是否为外来物种"},{key:12,prop:"exoticHarmLevel",label:"外来物种危害程度"},
        {key:13,prop:"isChinaEndemic",label:"是否为中国特有"},{key:14,prop:"isRegionEndemic",label:"是否为自治区特有"},
        {key:15,prop:"isNationalProtected",label:"是否为国家级保护物种"},{key:16,prop:"isRegionalProtected",label:"是否为自治区级保护物种"},
        {key:17,prop:"endangeredLevel",label:"濒危等级"},{key:18,prop:"threatReasons",label:"受威胁原因"},
        {key:19,prop:"distributionInProtected",label:"分布中心是否在保护地"},{key:20,prop:"statusInCommunity",label:"分布中心区物种在群落中的地位"},
        {key:21,prop:"habitatFeatures",label:"生境特征"},{key:22,prop:"mainValue",label:"主要价值"},
        {key:23,prop:"protectionStatus",label:"保护利用现状"},{key:24,prop:"speciesDescription",label:"物种描述"},
        {key:25,prop:"photoId",label:"照片编号"},{key:26,prop:"specimenId",label:"标本编号"}
      ],
      excelCurrentPage: 1,
      excelPageSize: 10,
    };
  },
  computed: {
    containerClass() {
      let pageHeight = document.documentElement.clientHeight-190;
      this.plant_container_style="max-height:"+pageHeight+"px;";
      return this.filteredPlants.length <= 5 ? "single-row" :"";
    },
    // Excel数据分页计算属性
    paginatedExcelData() {
      if (!this.excelData || !Array.isArray(this.excelData)) {
        return [];
      }
      const start = (this.excelCurrentPage - 1) * this.excelPageSize;
      const end = start + this.excelPageSize;
      return this.excelData.slice(start, end);
    },
  },

  mounted() {
    // 发送请求获取植物数据
   // this.fetchPlantData();
    this.handlezwk({
              pageNum: this.currentPage,
              pageSize: this.pageSize,
            });
    //this.getSmc();
    this.displayType = "全部"; // 设置默认显示全部
  },
  methods: {
    // 清空高级搜索选项
    handleClear() {
      this.selectedOption1 = ""; // 是否国家保护等级
      this.selectedOption2 = ""; // 是否红色名录濒危等级
      this.selectedOption3 = ""; // 是否中国特有
      this.selectedOption4 = ""; // 是否城市特有
      this.selectedOption5 = ""; // 是否自治区特有
      this.selectedOption6 = ""; // 分布中心是否在保护地
      this.selectedOption7 = ""; // 是否外来物种
      this.formData = {
        alien: null,
        centerinprotected: null,
        countryjb: null,
        countryjbdm: null,
        ischina: null,
        ischinadm: null,
        iscites: null,
        iscitesdm: null,
        jlr: null,
        provinceunique: null,
        redjb: null,
        redjbdm: null,
        sdm: null,
        smc: null,
        tuming: null,
        wzmc: null,
        xmc: null,
      };
    },

    // 关闭高级搜索对话框
    handleDialogClose() {
      // 在关闭时清空表单数据
      this.handleClear();
      this.dialogFormVisible = false;
    },
    // 跳转到高级搜索页面

    goToAdvancedSearch() {
      // 在这里进行路由跳转
      this.$router.push({ name: "AdvancedSearch" });
    },
    handlezwk(searchParams){

      let that = this;
        let params = {
          this: that,
          url: config.webapiUrl+"nd/zw/getWzByCondition",
          data: {
            params: searchParams,
            headers: {
              Authorization: "Bearer " +getToken(),
            },
          },
          successFunc: function (response) {
            that.loading = false;
            let data = response.data.data;
            that.filteredPlants=data.list;
            that.totalPlant=data.total;
            
          },
          failFunc: function (response) {
            that.loading = false;
            let params = {
              this: that,
              title: "提示",
              message: "网络异常，请稍后重试！" + response,
              successFunc: function () {},
            };
            commonOper.showWarnAlert(params);
          },
        };
        commonOper.HttpGet(params);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.handlezwk({
         name:this.searchKeyword,
              pageNum: this.currentPage,
              pageSize: this.pageSize,
            });
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlezwk({
        name:this.searchKeyword,
              pageNum: this.currentPage,
              pageSize: this.pageSize,
            });
    },
    handleSearch() {
      const keyword = this.searchKeyword;

      // 如果没有关键词，返回全部植物数据
      let param={
        name:keyword,
        pageNum: this.currentPage,
              pageSize: this.pageSize,};
      this.handlezwk(param);
    },

    handleAddPlant() {
      this.$router.push({ name: "PlantAdd" });
    },
    handlePlantDeleted(deletedId) {
      // 本地数据删除逻辑
      const index = this.plants.findIndex((plant) => plant.id === deletedId);
      if (index !== -1) {
        this.plants.splice(index, 1);
        // 重新计算分页数据
        this.calculatePagination();
      }
    },
    calculatePagination() {
      console.log("人麻了", this.filteredPlants);

      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;

      // 只处理植物数据
      this.filteredPlants = this.plants
        .filter((plant) => plant.sdm && plant.sdm.startsWith("101"))
        .slice(start, end);
      console.log("人麻了", this.filteredPlants);
    },
    handleOptionChange1() {
      switch (this.selectedOption1) {
        case "01":
          this.formData.countryjb = "一级";
          this.formData.countryjbdm = "01";
          break;
        case "02":
          this.formData.countryjb = "二级";
          this.formData.countryjbdm = "02";
          break;
        case "03":
          this.formData.countryjb = "未列入";
          this.formData.countryjbdm = "03";
          break;
        default:
          // 其他情况的处理
          break;
      }
    },
    handleOptionChange2() {
      switch (this.selectedOption2) {
        case "01":
          this.formData.redjb = "濒危(EN)";
          this.formData.redjbdm = "01";
          break;
        case "02":
          this.formData.redjb = "地区绝灭(RE)";
          this.formData.redjbdm = "02";
          break;
        case "03":
          this.formData.redjb = "极危(CR)";
          this.formData.redjbdm = "03";
          break;
        case "04":
          this.formData.redjb = "近危(NT)";
          this.formData.redjbdm = "04";
          break;
        case "05":
          this.formData.redjb = "数据缺乏(DD)";
          this.formData.redjbdm = "05";
          break;
        case "06":
          this.formData.redjb = "未予评估(NE)";
          this.formData.redjbdm = "06";
          break;
        case "07":
          this.formData.redjb = "无危(LC)";
          this.formData.redjbdm = "07";
          break;
        case "08":
          this.formData.redjb = "易危(VU)";
          this.formData.redjbdm = "08";
          break;
        default:
          // 其他情况的处理
          break;
      }
    },
    handleOptionChange3() {
      switch (this.selectedOption3) {
        case "01":
          this.formData.ischina = "是";
          this.formData.ischinadm = "01";
          break;
        case "02":
          this.formData.ischina = "否";
          this.formData.ischinadm = "02";
          break;
        default:
          // 其他情况的处理
          break;
      }
    },
    handleOptionChange4() {
      switch (this.selectedOption4) {
        case "01":
          this.formData.iscites = "附录Ⅰ";
          this.formData.iscitesdm = "01";
          break;
        case "02":
          this.formData.iscites = "附录Ⅱ";
          this.formData.iscitesdm = "02";
          break;
        case "03":
          this.formData.iscites = "未列入";
          this.formData.iscitesdm = "03";
          break;
        default:
          // 其他情况的处理
          break;
      }
    },
    handleOptionChange5() {
      switch (this.selectedOption5) {
        case "01":
          this.formData.provinceunique = "是";

          break;
        case "02":
          this.formData.provinceunique = "否";

          break;
        default:
          // 其他情况的处理
          break;
      }
    },
    handleOptionChange6() {
      switch (this.selectedOption6) {
        case "01":
          this.formData.centerinprotected = "是";
          break;
        case "02":
          this.formData.centerinprotected = "否";
          break;
        default:
          // 其他情况的处理
          break;
      }
    },
    handleOptionChange7() {
      switch (this.selectedOption7) {
        case "01":
          this.formData.alien = "是";
          break;
        case "02":
          this.formData.alien = "否";
          break;
        default:
          // 其他情况的处理
          break;
      }
    },
    // 去除空格
    removeSpaces(str) {
      // 根据需要保留或去除空格
      return str.replace(/\s/g, ""); // 这里是去除空格
    },
    // 属名称
    handleCascaderChange(selectedValues) {
      console.log("vvvv", selectedValues);
      this.formData.sdm = selectedValues[selectedValues.length - 1]; // 例如，将最后一个值作为 smc
      const selectedData = this.findDataBySdm(this.formData.sdm);
      this.formData.smc = selectedData.dmmc1;
    },
    findDataBySdm(sdm) {
      const selectedData = this.filteredData.find((item) => item.dmz === sdm);
      console.log("666", selectedData);
      return selectedData || null;
    },
    getSmc() {
      this.$api
        .getSmcData()
        .then((res) => {
          console.log("res", res);
          // 处理科的数据
          const scientificOptions = [];
          this.filteredData = res.data.data;
          // console.log("数据", this.filteredData);
          // 找到所有的科
          const scientificData = this.filteredData.filter(
            (item) => item.jb === "5"
          );
          // console.log("222", scientificData);
          // 遍历科，为每个科添加属
          scientificData.forEach((scientific) => {
            const speciesInScientific = this.filteredData.filter(
              (item) => item.jb === "6" && item.dmz.includes(scientific.dmz)
            );

            const speciesOptions = speciesInScientific.map((species) => ({
              value: species.dmz,
              label: species.dmmc1,
            }));
            // console.log("aa", speciesOptions);
            scientificOptions.push({
              value: scientific.dmz,
              label: scientific.dmmc1,
              children: speciesOptions,
            });
          });
          // console.log("bbbb", scientificOptions);
          // 设置给 options
          this.options = scientificOptions;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 高级搜索
    handleAdvancedSearch() {
      console.log(this.formData);
      // 构建过滤条件对象
      const filterConditions = {};
      // 物种名称
      if (this.formData.wzmc) {
        filterConditions.wzmc = this.removeSpaces(this.formData.wzmc);
      }
      // 学名，拉丁名
      if (this.formData.xmc) {
        filterConditions.xmc = this.removeSpaces(this.formData.xmc);
      }
      // 土名
      if (this.formData.tuming) {
        filterConditions.tuming = this.removeSpaces(this.formData.tuming);
      }
      // 记录人
      if (this.formData.jlr) {
        filterConditions.jlr = this.removeSpaces(this.formData.jlr);
      }
      // 是否列入国家保护等级
      if (this.formData.countryjbdm) {
        filterConditions.countryjbdm = this.formData.countryjbdm;
      }
      // 是否红色名录濒危等级
      if (this.formData.redjbdm) {
        filterConditions.redjbdm = this.formData.redjbdm;
      }
      // 是否中国特有
      if (this.formData.ischinadm) {
        filterConditions.ischinadm = this.formData.ischinadm;
      }
      // 是否城市特有
      if (this.formData.iscitesdm) {
        filterConditions.iscitesdm = this.formData.iscitesdm;
      }
      // 是否自治区特有
      if (this.formData.provinceunique) {
        filterConditions.provinceunique = this.formData.provinceunique;
      }
      // 分布中心是否在保护地
      if (this.formData.centerinprotected) {
        filterConditions.centerinprotected = this.formData.centerinprotected;
      }
      // 是否外来物种
      if (this.formData.alien) {
        filterConditions.alien = this.formData.alien;
      }
      // 属名称
      if (this.formData.sdm) {
        filterConditions.sdm = this.formData.sdm;
      }

      // 添加其他字段的条件，根据需要继续添加
      console.log("所有数据长度", this.plants.length);

      // 使用过滤条件对象进行过滤，只搜索植物数据
      const advancedSearchResult = this.plants.filter((plant) => {
        // 首先确保是植物数据
        if (!plant.sdm || !plant.sdm.startsWith("101")) {
          return false;
        }
        // 判断每个字段是否满足条件
        return Object.keys(filterConditions).every((key) => {
          return plant[key] && plant[key].includes(filterConditions[key]);
        });
      });

      // 更新结果到页面
      console.log("好烦", advancedSearchResult);

      this.filteredPlants = advancedSearchResult;
      this.currentPage = 1; // 重置页码
      this.dialogFormVisible = false; // 关闭高级搜索对话框
      this.handleClear();
      // this.calculatePagination();
    },

    // Excel导入相关方法
    handleExcelImport() {
      // 创建文件输入元素
      const input = document.createElement("input");
      input.type = "file";
      input.accept = ".xlsx,.xls";
      input.onchange = (event) => {
      const file = event.target.files[0];
      readPlantBasicInfo(file).then((data) => {
      // Promise 解析成功，获取数据
      this.excelData=data;
      this.excelCurrentPage = 1;
      this.excelImportDialogVisible = true;
      this.$message.success(`成功读取Excel文件，共${data.length}条数据`);
    }).catch((error) => {
      console.error('读取 Excel 文件出错:', error);});
      };
      input.click();
    },
    // Excel分页大小改变
    handleExcelSizeChange(val) {
      this.excelPageSize = val;
    },

    // Excel当前页改变
    handleExcelCurrentChange(val) {
      this.excelCurrentPage = val;
    },

    // 关闭Excel导入对话框
    handleExcelDialogClose() {
      this.excelImportDialogVisible = false;
      this.excelData = [];
      this.excelCurrentPage = 1;
    },

    // 确认导入Excel数据
    handleConfirmImport() {
      if (!this.excelData || this.excelData.length === 0) {
        this.$message.warning("没有数据可导入");
        return;
      }
      let jsonData={
        frontNdAnimalSpecies:[],
        frontNdPlantSpecies:this.excelData
      };
      let that=this;
      let paramscommo = {
        this: that,
        url: config.webapiUrl+"nd/zwdw/addSpeciesBat",
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        data: jsonData,
        successFunc: function (response) {
          
          if (response.data.code == 0) {
            this.excelImportDialogVisible = false;
            that.$message.success("保存成功！");
          } else {
            let params = {
              this: that,
              title: "提示",
              message: "保存失败，请稍后重试！" + response.data.msg,
              successFunc: function () {},
            };
            commonOper.showWarnAlert(params);
          }
        },
        failFunc: function (response) {
          
          let params = {
            this: that,
            title: "提示",
            message: "网络异常，请稍后重试！" + response.data.data,
            successFunc: function () {},
          };
          commonOper.showWarnAlert(params);
        },
      };
      commonOper.HttpPost(paramscommo);
    },
    // 辅助方法：获取国家保护等级代码
    getCountryJbDm(value) {
      const mapping = {
        一级: "01",
        二级: "02",
        未列入: "03",
      };
      return mapping[value] || null;
    },

    // 辅助方法：获取红色名录濒危等级代码
    getRedJbDm(value) {
      const mapping = {
        "濒危(EN)": "01",
        "地区绝灭(RE)": "02",
        "极危(CR)": "03",
        "近危(NT)": "04",
        "数据缺乏(DD)": "05",
        "未予评估(NE)": "06",
        "无危(LC)": "07",
        "易危(VU)": "08",
      };
      return mapping[value] || null;
    },

    // 辅助方法：获取是否中国特有代码
    getIsChinaDm(value) {
      const mapping = {
        是: "01",
        否: "02",
      };
      return mapping[value] || null;
    },

    // 辅助方法：获取是否城市特有代码
    getIsCitesDm(value) {
      const mapping = {
        附录Ⅰ: "01",
        附录Ⅱ: "02",
        未列入: "03",
      };
      return mapping[value] || null;
    },
  },
};
</script>

<style scoped>
/* 样式可以根据需要进行调整 */
.box {
  text-align: center;
  margin: 20px;
}

h1 {
  color: #41b883;
}

.plant-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  overflow-y: auto;
  /**max-height: 68vh;**/
}
.plant-container.single-row {
  overflow-y: hidden; /* 只有一行时隐藏滚动条 */
}
/* 调整每个 plant-item 的宽度 */
.plant-item {
  width: 18%; /* 或者其他合适的宽度，根据实际情况调整 */
  margin-bottom: 10px;
}
/* .dialog-content {
  display: flex;
  flex-direction: column;
} */
/* .dialog-content {
  text-align: left;
} */
.el-form-item__label {
  text-align: left;
}
/* .demo-form-inline .el-form-item__label {
  text-align: left;
  width: 120px;
  margin-right: 10px;
} */

@media (min-width: 768px) {
  .plant-item {
    flex: 0 0 18%; /* 每行显示 5 个植物，可以根据需要调整 */
  }
}

/* Excel导入相关样式 */
.excel-preview-container {
  padding: 20px 0;
}

.excel-pagination {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  text-align: center;
}

/* Excel表格样式优化 */
.excel-preview-container .el-table {
  font-size: 14px;
}

.excel-preview-container .el-table th {
  font-weight: bold !important;
  background-color: #f5f7fa !important;
  color: #303133 !important;
}

.excel-preview-container .el-table td {
  padding: 8px 0;
}

.excel-preview-container
  .el-table--striped
  .el-table__body
  tr.el-table__row--striped
  td {
  background-color: #fafafa;
}
.el-image-viewer__mask{
      opacity: .9;
}
</style>
